#!/usr/bin/python
# encoding:utf-8
#from __future__ import division
import cv2
import numpy as np



#找一位数组中找到分割位置
def min_pos_find(rows,threshold):

    start = 0
    end  = 0
    posinfo = []
    #rowimgs = []
    for index,value in enumerate(rows):

        if start == 0:
            if value > threshold:
                start = index
        else:
            if value <= threshold:
                end = index
                posinfo.append((start,end))
                #rowimgs.append(imgori[start:end,0:imgori.shape[1]])
                start = 0
                #Ecv2.imshow(str(index), rowimgs[-1])
    return posinfo

#根据数据分割
def img_pos_spliter(imgori, posinfo, axis):
    imgsets = []
    for pos in posinfo:
        if axis == 1:
            imgsets.append(imgori[0:imgori.shape[0]+1, pos[0]-1:pos[1]+1])
        else:
            imgsets.append(imgori[pos[0]-1:pos[1]+1, 0:imgori.shape[1]+1])
        #cv2.imshow(str(pos[0]), imgsets[-1])
    return imgsets




def spliter_word(imgori, row_threshhold, col_threshold):

    # 直接用二值化，不做膨胀什么的

    # 二值化
    # img1 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
    # cv2.THRESH_BINARY,5,1)
    # cv2.imshow('img1',img1)

    # 最简单的二值化
    # ret,img1 = cv2.threshold(img,100,255,cv2.THRESH_BINARY)
    # cv2.imshow('img1',img1)


    # otsu二值化
    ret, img1 = cv2.threshold(imgori, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    #cv2.imshow('img1', img1)

    #水平投影 分割行 其实就是把水平方向的像素相加,除以宽度，最大255的像素统计数组

    rowpixcounts = img1.sum(axis=1) / img1.shape[1]
    #print len(rowpixcounts)
    #print rowpixcounts

    rowposinfo = min_pos_find(rowpixcounts, row_threshhold)

    #二值化的文字行
    rowimgsets = img_pos_spliter(img1, rowposinfo, 0)


    #print  rowposinfo

    singleword_imgset = []

    for index,rowimg in enumerate(rowimgsets):

        colpixcounts = rowimg.sum(axis=0) / rowimg.shape[1]
#        print len(colpixcounts)
#        print colpixcounts


        colposinfo = min_pos_find(colpixcounts, col_threshold)
        colimgsets = img_pos_spliter(rowimg, colposinfo, 1)


        #print  colposinfo
        #print ( map(lambda (x,y):y-x,colposinfo))

        for imgx in colimgsets:
            h,w = imgx.shape

            if w / h < 0.2:
                pass
            elif  w / h < 1.5:
                singleword_imgset.append(imgx)
            else:
                #or i in range( round(w/h)-1):
                #print w / h

                len = int(round(w/h))
                neww = int(round(w/len))
                for j in range(len):
                    #cv2.imshow('hahahahaha' +str(j)+str(i), imgx[0:h,j*neww:(j+1)*neww])
                    singleword_imgset.append(imgx[0:h,j*neww:(j+1)*neww])

        #img_pos_spliter(rowimg, colposinfo, 1)
        #for posinfo in colposinfo:
            #print  rowposinfo[0]
            #cv2.rectangle(img, (posinfo[0],rowposinfo[index][0]),(posinfo[1],rowposinfo[index][1]),(0,255,0),1)
    return singleword_imgset

#cv2.imshow('img',img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()


if __name__ == '__main__':
    img = cv2.imread(r'C:\Users\he\Desktop\pp.png',0)
    imgset = spliter_word(img,5,0.5)
    #保存到桌面！
    index = 0
    for img in imgset:
        index += 1
        cv2.imwrite(r'C:\Users\he\Desktop\tmp\00%d.png' % index, img)


